package com.sinszm.mdb;

import cn.hutool.db.Db;
import cn.hutool.db.Session;
import com.sinszm.mdb.annotation.Mdb;
import com.sinszm.mdb.support.MdbConstant;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.annotation.Resource;
import javax.sql.DataSource;

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

/**
 * Mybatis与数据库连接池自动配置
 *
 * @author chenjianbo
 */
@Mdb
@PropertySource("classpath:mdb.properties")
@EnableTransactionManagement
public class SzmMdbAutoConfiguration implements TransactionManagementConfigurer {

    @Resource
    private DataSource dataSource;

    @Bean(MdbConstant.TRANSACTION_MANAGER)
    @Primary
    public PlatformTransactionManager mdbManager() {
        DataSourceTransactionManager manager = new DataSourceTransactionManager();
        manager.setDataSource(dataSource);
        manager.setRollbackOnCommitFailure(true);
        return manager;
    }

    @Resource
    @Qualifier(MdbConstant.TRANSACTION_MANAGER)
    private PlatformTransactionManager mdbManager;

    /**
     * 默认事务采用JDBC事务
     */
    @Override
    public TransactionManager annotationDrivenTransactionManager() {
        return mdbManager;
    }

    /**
     * 方式一，代码式数据操作实例
     * <p>
     *     mysql,oracle
     * </p>
     * @return  操作实例
     */
    @ConditionalOnExpression(
            "'${spring.datasource.platform:}'.equalsIgnoreCase('mysql')||'${spring.datasource.platform:}'.equalsIgnoreCase('oracle')"
    )
    @Bean("mDb")
    @Scope(SCOPE_PROTOTYPE)
    public Db mDb() {
        return Db.use(dataSource);
    }

    /**
     * 方式二，代码式数据操作实例
     * <p>
     *     mysql,oracle
     * </p>
     * @return  操作实例
     */
    @ConditionalOnExpression(
            "'${spring.datasource.platform:}'.equalsIgnoreCase('mysql')||'${spring.datasource.platform:}'.equalsIgnoreCase('oracle')"
    )
    @Bean("mDbs")
    @Scope(SCOPE_PROTOTYPE)
    public Session mDbs() {
        return Session.create(dataSource);
    }

}